package com.photography.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photography.common.JwtTokenUtils;
import com.photography.common.Result;
import com.photography.entity.Photographers;
import com.photography.exception.ErrorCode;
import com.photography.mapper.PhotographersMapper;
import com.photography.service.PhotographersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class PhotographersServiceImpl extends ServiceImpl<PhotographersMapper, Photographers> implements PhotographersService {
    /**
     * 摄影师注册
     *
     * @param photographers 摄影师信息
     * @return 注册结果
     */
    @Override
    public Result register(Photographers photographers) {
        if (!StringUtils.hasText(photographers.getName())) {
            return Result.error("摄影师姓名不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(photographers.getContactInfo())) {
            return Result.error("联系方式不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(photographers.getAccount())) {
            return Result.error("账号不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(photographers.getPassword())) {
            return Result.error("密码不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        //检查账号是否被使用
        Photographers findPhotographers = this.getOne(
                new QueryWrapper<Photographers>().eq("account", photographers.getAccount())
        );
        if (findPhotographers != null) {
            return Result.error("此账号已被注册");
        }

        //设置默认角色
        if (!StringUtils.hasText(photographers.getRole())){
            photographers.setRole("employee");
        }

        //设置创建时间和更新时间
        Date now=new Date();
        photographers.setCreateTime(now);
        photographers.setUpdateTime(now);

        boolean result = this.save(photographers);
        if (result) {
            return Result.successWithMsg("注册成功");
        } else {
            return Result.error("注册失败");
        }
    }

    /**
     * 摄影师登录
     *
     * @param account  账号
     * @param password 密码
     * @return 登录结果
     */
    @Override
    public Result login(String account, String password) {
        if (!StringUtils.hasText(account) || !StringUtils.hasText(password)) {
            return Result.error("账号或密码不能为空", ErrorCode.USER_LOGIN_ERROR.getCode());
        }

        LambdaQueryWrapper<Photographers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Photographers::getAccount, account)
                .eq(Photographers::getPassword, password);
        Photographers photographer = this.getOne(wrapper);

        if (photographer == null) {
            return Result.error("账号或密码错误", ErrorCode.USER_LOGIN_ERROR.getCode());
        }

        // 生成token，添加角色信息
        String token = JwtTokenUtils.getToken(photographer.getPhotographerId().toString(), photographer.getPassword(), photographer.getRole());
        Map<String, Object> data = new HashMap<>();
        data.put("photographer", photographer);
        data.put("token", token);

        return Result.success(data, "登录成功");
    }

    /**
     * 更新摄影师信息
     * @param photographers 摄影师信息
     * @return 结果
     */
    @Override
    public Result updatePhotographers(Photographers photographers) {
        if (photographers.getPhotographerId()==null){
            return Result.error("摄影师id不能为空",ErrorCode.PARAM_EMPTY.getCode());
        }
        Photographers findPhotographers= this.getById(photographers.getPhotographerId());
        if (findPhotographers==null){
            return Result.error("没有此摄影师",ErrorCode.USER_LOGIN_ERROR.getCode());
        }
        String photographerRole=JwtTokenUtils.getCurrentRole();
        Integer photographerId= Objects.requireNonNull(JwtTokenUtils.getCurrentPhotographer()).getPhotographerId();
        if (!photographerId.equals(photographers.getPhotographerId())){
            if (!Objects.equals(photographerRole, "manager")){
                return Result.error("只能修改自己的信息");
            }
        }
        //检查账号是否被使用
        if (StringUtils.hasText(photographers.getAccount())){
            Photographers findAccount=this.getOne(
                    new QueryWrapper<Photographers>().eq("account",photographers.getAccount())
            );
            if (findAccount!=null && !findAccount.getAccount().equals(photographers.getAccount())){
                return Result.error("此账号已被使用",ErrorCode.DATA_ALREADY_EXIST.getCode());
            }
        }

        boolean result=this.updateById(photographers);
        if (result){
            return Result.success(photographers,"更新成功");
        }else {
            return Result.error("更新失败");
        }
    }

    /**
     * 重置密码
     * @param photographerId id
     * @return 结果
     */
    @Override
    public Result resetPassword(Integer photographerId) {
        if (photographerId==null){
            return Result.error("摄影师id不能为空",ErrorCode.PARAM_EMPTY.getCode());
        }
        Photographers photographers=this.getById(photographerId);
        photographers.setPassword(photographers.getContactInfo());
        boolean result=this.updateById(photographers);
        if (result){
            return Result.success(photographers,"重置密码成功");
        }else {
            return Result.error("重置密码失败");
        }
    }

    /**
     * 删除摄影师
     * @param photographerId id
     * @return 结果
     */
    @Override
    public Result deletePhotographers(Integer photographerId) {
      if (photographerId==null){
          return Result.error("id不能为空",ErrorCode.PARAM_EMPTY.getCode());
      }
      Photographers photographers=this.getById(photographerId);
      if (photographers==null){
          return Result.error("此摄影师不存在",ErrorCode.DATA_NOT_EXIST.getCode());
      }
      boolean result=this.removeById(photographerId);
        if (result) {
            return Result.success(null, "删除成功");
        } else {
            return Result.error("删除失败");
        }

    }

    /**
     * 分页查询摄影师
     * @param page 分页参数
     * @param gender 性别（可选）
     * @param role 角色（可选）
     * @param search 搜索关键词，支持用户名、擅长领域、邮箱、手机号、昵称的模糊匹配
     * @return 结果
     */
    @Override
    public Page<Photographers> getPhotographersPage(Page<Photographers> page, String gender,String role,String search) {
        // 创建查询条件
        LambdaQueryWrapper<Photographers> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(gender)) {
            queryWrapper.eq(Photographers::getGender, gender);
        }
        if (StringUtils.hasText(role)){
            queryWrapper.eq(Photographers::getRole,role);
        }
        if (StringUtils.hasText(search)){
            queryWrapper.like(Photographers::getName, search)
                    .or()
                    .like(Photographers::getContactInfo, search)
                    .or()
                    .like(Photographers::getExpertise, search)
                    .or()
                    .like(Photographers::getWorkExperience, search)
                    .orderByDesc(Photographers::getCreateTime);
        }

        // 按注册时间降序排序
        queryWrapper.orderByDesc(Photographers::getCreateTime);

        // 执行分页查询
        return page(page, queryWrapper);
    }

    /**
     * 模糊搜索
     * @param page 分页参数
     * @param keyword 搜索关键词，支持用户名、擅长领域、邮箱、手机号、性别的模糊匹配
     * @return 结果
     */
    @Override
    public Page<Photographers> search(Page<Photographers> page, String keyword) {
        if (!StringUtils.hasText(keyword)) {
            return new Page<>(page.getCurrent(), page.getSize());
        }

        // 创建查询条件
        LambdaQueryWrapper<Photographers> wrapper = new LambdaQueryWrapper<Photographers>()
                .like(Photographers::getName, keyword)
                .or()
                .like(Photographers::getGender, keyword)
                .or()
                .like(Photographers::getContactInfo, keyword)
                .or()
                .like(Photographers::getExpertise, keyword)
                .or()
                .like(Photographers::getWorkExperience, keyword)
                .or()
                .like(Photographers::getGender, keyword)
                .orderByDesc(Photographers::getCreateTime);

        // 执行分页查询
        Page<Photographers> resultPage = this.page(page, wrapper);
        
        // 获取当前登录用户的角色
        String currentRole = JwtTokenUtils.getCurrentRole();
        
        // 如果不是管理员，只返回指定字段
        if (!"manager".equals(currentRole)) {
            resultPage.getRecords().forEach(photographer -> {
                // 只保留需要的字段
                photographer.setAccount(null);
                photographer.setPassword(null);
                photographer.setRole(null);
                photographer.setCreateTime(null);
                photographer.setUpdateTime(null);
                photographer.setPortfolioLinks(null);
            });
        }
        
        return resultPage;
    }
}
